import mongoose from '../config/dbHelper';
import moment from 'moment';

const Schema = mongoose.Schema;
const PostSchema = new Schema({
  uid: { type: String, ref: 'users' },
  title: { type: String },
  content: { type: String },
  created: { type: Date },
  catalog: { type: String },
  fav: { type: String },
  isEnd: { type: String },
  reads: { type: Number },
  answer: { type: Number },
  status: { type: String },
  isTop: { type: String },
  sort: { type: String },
  tags: { type: Array }
});

PostSchema.statics = {
  /**
   * 获取文章列表数据
   * @param {查询的条件} options
   * @param {排序的字段和升降序} sort
   * @param {查询页数} page
   * @param {查询条数} limit
   */
  getList: function (options, sort, page, limit) {
    return this.find(options, { content: 0 })
      // 指定变量为属性名，采用[]包裹
      .sort({ [sort]: -1 })
      .skip(limit * page)
      .limit(limit)
      .populate({
        path: 'uid',
        select: 'username isVip pic'
      });
  },

  // 获取热议文章数据
  getHotList: function () {
    return this.find({
      created: {
        // 筛选创建时间为一个月内的文章数据
        $gte: moment().subtract(1, 'months')
      }
    }, {
      title: 1,
      answer: 1
    })
      .sort({ answer: -1 })
      .limit(10);
  },

  // 获取指定文章数据
  getTopList: function () {
    return this.find({ isTop: '1' }, { content: 0 })
    // 指定变量为属性名，采用[]包裹
      .sort({ sort: -1 })
      .populate({
        path: 'uid',
        select: 'username isVip pic'
      });
  }
};

PostSchema.pre('save', function (next) {
  this.created = moment().format('YYYY-MM-DD HH:mm:ss');
  next();
});

const PostModel = mongoose.model('posts', PostSchema);
export default PostModel;
